package com.travel.filter;

import com.travel.service.AppUserService;
import com.travel.util.SignUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import java.io.IOException;
import java.util.Map;

public class SecurityFilter implements Filter {

    private AppUserService appUserService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
        appUserService = (AppUserService) ctx.getBean("appUserServiceImpl");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Map<String, String[]> params = servletRequest.getParameterMap();
        String sign = servletRequest.getParameter("sign");//传进来的签名
        String appId = servletRequest.getParameter("appid");
        try {
            if (StringUtils.isEmpty(sign) || StringUtils.isEmpty(appId)) {
                throw new Exception("参数错误");
            }
            String secretKey = appUserService.getSecretKey(appId);
            String signString = SignUtil.getSign(params);
            String mySign = DigestUtils.md5DigestAsHex((signString + secretKey).getBytes());
            System.out.println(sign);
            System.out.println(mySign);
            if (mySign.equals(sign)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                throw new Exception("签名错误");
            }
        } catch (Exception e) {
            servletResponse.setCharacterEncoding("utf-8");
            servletResponse.setContentType("application/json; charset=UTF-8");
            String json = "{\"status\":false,\"message\":\"" + e.getMessage() + "\"}";
            servletResponse.getWriter().print(json);
        }
    }

    @Override
    public void destroy() {

    }
}
